/*
 * Copyright [2022] [https://www.xiaonuo.vip]
 *
 * Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：
 *
 * 1.请不要删除和修改根目录下的LICENSE文件。
 * 2.请不要删除和修改Snowy源码头部的版权声明。
 * 3.本项目代码可免费商业使用，商业使用请保留源码和相关描述文件的项目出处，作者声明等。
 * 4.分发源码时候，请注明软件出处 https://www.xiaonuo.vip
 * 5.不可二次分发开源参与同类竞品，如有想法可联系团队xiaonuobase@qq.com商议合作。
 * 6.若您的项目无法满足以上几点，需要更多功能代码，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package com.bishe.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bishe.entity.AskLeave;
import com.bishe.entity.User;
import com.bishe.entity.resp.CommonPageRequest;
import com.bishe.entity.resp.CommonSortOrderEnum;
import com.bishe.exception.CommonException;
import com.bishe.mapper.AskLeaveMapper;
import com.bishe.param.AskLeaveAddParam;
import com.bishe.param.AskLeaveEditParam;
import com.bishe.param.AskLeaveIdParam;
import com.bishe.param.AskLeavePageParam;
import com.bishe.service.AskLeaveService;
import com.bishe.service.TeacherService;
import com.bishe.service.UserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * ask_leaveService接口实现类
 *
 * @author wwz
 * @date  2024/03/11 13:21
 **/
@Service
public class AskLeaveServiceImpl extends ServiceImpl<AskLeaveMapper, AskLeave> implements AskLeaveService {

    private final static List<String> monthList = Arrays.asList("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12");


    @Resource
    private UserService userService;

    @Resource
    private TeacherService teacherService;

    @Override
    public Page<AskLeave> page(AskLeavePageParam askLeavePageParam) {
        QueryWrapper<AskLeave> queryWrapper = new QueryWrapper<>();
        if (ObjectUtil.isAllNotEmpty(askLeavePageParam.getSearchKey(), askLeavePageParam.getSearchValue())) {
            queryWrapper.eq(true, StrUtil.toUnderlineCase(askLeavePageParam.getSearchKey()), askLeavePageParam.getSearchValue());
        }

        if(ObjectUtil.isAllNotEmpty(askLeavePageParam.getSortField(), askLeavePageParam.getSortOrder())) {
            CommonSortOrderEnum.validate(askLeavePageParam.getSortOrder());
            queryWrapper.orderBy(true, askLeavePageParam.getSortOrder().equals(CommonSortOrderEnum.ASC.getValue()),
                    StrUtil.toUnderlineCase(askLeavePageParam.getSortField()));
        } else {
            queryWrapper.lambda().orderByAsc(AskLeave::getId);
        }
        Page<AskLeave> page = this.page(CommonPageRequest.defaultPage(), queryWrapper);

        for (AskLeave askLeave : page.getRecords()) {
            User user = userService.getById(askLeave.getQjr());
            if (ObjectUtil.isNotEmpty(user)){
                askLeave.setQjrName(user.getName());
            }
        }
        return page;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(AskLeaveAddParam askLeaveAddParam) {
        AskLeave askLeave = BeanUtil.toBean(askLeaveAddParam, AskLeave.class);
        askLeave.setQjr(StpUtil.getLoginIdAsString());
        this.save(askLeave);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(AskLeaveEditParam askLeaveEditParam) {
        AskLeave askLeave = this.queryEntity(askLeaveEditParam.getId());
        BeanUtil.copyProperties(askLeaveEditParam, askLeave);
        this.updateById(askLeave);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<AskLeaveIdParam> askLeaveIdParamList) {
        // 执行删除
        this.removeByIds(CollStreamUtil.toList(askLeaveIdParamList, AskLeaveIdParam::getId));
    }

    @Override
    public AskLeave detail(AskLeaveIdParam askLeaveIdParam) {
        return this.queryEntity(askLeaveIdParam.getId());
    }

    @Override
    public AskLeave queryEntity(String id) {
        AskLeave askLeave = this.getById(id);
        if(ObjectUtil.isEmpty(askLeave)) {
            throw new CommonException("ask_leave不存在，id值为：{}", id);
        }

        User user = userService.getById(askLeave.getQjr());
        if (ObjectUtil.isNotEmpty(user)){
            askLeave.setQjrName(user.getName());
        }
        return askLeave;
    }

    @Override
    public List<AskLeave> myAskLeave() {
        StpUtil.checkLogin();
        List<AskLeave> list = list(Wrappers.lambdaQuery(AskLeave.class)
                .in(AskLeave::getUid, StpUtil.getLoginIdAsString()));
        list.forEach(s->s.setQjrName(userService.getById(s.getQjr()).getName()));
        return list;
    }

    @Override
    public  Map<Object, Object> tj() {
        List<AskLeave> list = list();
        if (CollUtil.isEmpty(list)){
            return new HashMap<>();
        }

        Map<Integer, List<AskLeave>> map = list.stream().collect(Collectors.groupingBy(s -> DateUtil.month(s.getCreateTime())));

        Map<Object, Object> result = new HashMap<>();
        for (Map.Entry<Integer, List<AskLeave>> entry : map.entrySet()) {
            Integer key = entry.getKey();
            for (String month : monthList) {
                if(String.valueOf(key).equals(month)){
                    int size = entry.getValue().size();
                    result.put(key.toString(), size);
                }else {
                    result.put(month, 0);
                }
            }
        }
        return result;
    }
}
